package cn.wn.web;

import cn.wn.model.ResultInfo;
import cn.wn.pojo.User;
import cn.wn.service.UserService;
import cn.wn.shiro.ShiroRealm;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Api 注解：
 * 1、指定当前的生成文档的模块
 * 2、tags 指定模块的描述名称
 */
@RestController
@RequestMapping("user")
@Api(tags = "用户管理")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据id查询
     */
    @RequiresPermissions("user:find")
    @GetMapping("{id}")
    @ApiOperation(value = "根据id查询")
    public ResultInfo<User> findOne(@PathVariable("id") Integer id) {
        log.info("权限校验成功！");
        //SecurityUtils.getSubject().checkPermission("user:find");
        User user = userService.findById(id);
        return ResultInfo.ok(user);
    }

    /**
     * 查询全部
     */
    @RequiresPermissions("user:find")
    @GetMapping
    @ApiOperation(value = "查询全部")
    public ResultInfo<List<User>> findAll(){
        List<User> list = userService.findAll();
        return ResultInfo.ok(list);
    }
    /**
     * 分页查询全部
     * 举例： http://localhost:8080/user/page/1/5
     */
    @RequiresPermissions("user:find")
    @GetMapping("/page/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询全部")
    public ResultInfo<PageInfo> findByPage(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize){
        PageInfo<User> pageInfo = userService.findByPage(pageNum,pageSize);
        return ResultInfo.ok(pageInfo);
    }

    /**
     * 添加
     */
    @RequiresPermissions("user:add")
    @PostMapping
    @ApiOperation(value = "添加")
    public ResultInfo<String> save(@RequestBody User user){
        userService.save(user);
        return ResultInfo.ok("添加成功");
    }

    /**
     * 修改
     */
    @RequiresPermissions("user:update")
    @PutMapping
    @ApiOperation(value = "修改")
    public ResultInfo<String> update(@RequestBody User user){
        userService.update(user);
        return ResultInfo.ok();
    }

    /**
     * 删除
     */
    @RequiresPermissions("user:delete")
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除")
    public ResultInfo<String> delete(@PathVariable("id") Integer id){
        userService.delete(id);
        return ResultInfo.ok();
    }
}
